# -*- coding:utf-8 -*-
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from channels.exceptions import StopConsumer, AcceptConnection, DenyConnection, InvalidChannelLayerError
from asgiref.sync import async_to_sync
import json

from django.core.cache import cache
import logging

logger = logging.getLogger("django")


class SKUserView(WebsocketConsumer):
    """
    发送同步菜单，同步退出登陆
    """

    # groups 记录当前登陆的用户
    # groups = ["admin1", "admin2"]

    def websocket_connect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        logger.info(group)
        logger.info(self.channel_name)

        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)

        try:
            self.connect()
        except AcceptConnection:
            self.accept()
        except DenyConnection:
            self.close()

    def websocket_disconnect(self, message):
        group = self.scope["url_route"]["kwargs"].get("pk")
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        raise StopConsumer()

    def websocket_receive(self, message):
        """
        Called when a WebSocket frame is received. Decodes it and passes it
        to receive().
        """
        if "text" in message:
            if message["text"] == "ping":
                self.send("pong")
        else:
            logger.info(message["bytes"])

    def sendMsg(self, event):
        text = event["text"]
        # logger.info(text)
        self.send(text)
        """
        {"isLogin":true,"menu":""}
        """
